<template>
  <t-dialog v-model:visible="visible" attach="body" header="选择预算模板" width="28%">
    <div class="container">
      <t-tabs v-model:value="type" :list="list" placement="left"  @change="handleChangeMaterial" />
      <t-space class="right" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
          v-if="type==='1'"
        />
      
        <!-- 类目树 -->
        <t-tree
          v-if="type==='1'"
          :data="categoryTree"
          activable
          v-model:actived="actived"
          v-model:expanded="expanded"
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
          :label="getLabel"
        />
        <t-tree
          v-else
          :data="categoryTree2"
          activable
          v-model:actived="actived"
          v-model:expanded="expanded"
          expand-on-click-node
          hover
          :keys="{ label: 'address', value: 'orderId' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
          :label="getLabel"
        />
      </t-space>
     
    </div>
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button>
    </template>
  </t-dialog>
  <t-dialog
      attach="body"
      v-model:visible="visible1"
      theme="info"
      header="提示"
      body="确认要引用该方案吗？引用后会覆盖原数据，请谨慎！"
      :on-close="close1"
      :cancel-btn="null"
      @confirm="onClickConfirm"
    />
</template>

<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { getCompanyList } from '@/api/system/dept';

import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';
import { budgeModelCRUD } from '@/api/budget/model';
import { getBudgetHistory } from '@/api/order/details';

const dictionaryStore = useDictionaryStore();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['update:visible', 'save']);

const visible = ref(props.visible);
const companyId = ref();
const companySimpleList = ref([]);
const categoryList = ref([]);
const categoryTree = ref([]);
const categoryTree2 = ref([]);
const selectedId = ref();
const actived = ref([]);
const expanded = ref([]);
const loadingSubmit = ref(false);
const visible1 = ref(false);
const close1 = () => {
  visible1.value = false;
};
const onClickConfirm = (context: { e: any; }) => {
  const { e } = context;
  visible1.value = false;
  emits('save', {
    type: type.value,
    id: selectedId.value,
  });
  visible.value = false;
  e.stopPropagation();
};
// 默认材料类型
const type = ref('1')
// tab
const list = ref([
  { label: '公司预算模板', value: '1' },
  { label: '引入历史预算', value: '2' },
])
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    companyId.value = data[0].id;
  });
};

const typeOption = [{label:'套餐报价', value:'1'},{label:'清单报价', value:'2'}]

const getLabel = (h: any, node: { data: any; }) => {
  const { data } = node;
  if(type.value==='1') return `${data.name}(${typeOption.find((item) => item.value === data.type)?.label})`
  if(type.value==='2') return `${data.address}(${data.houseArea}㎡)`
};
const handleGetCategory = () => {
 
  if(type.value==='1') {
    const params = {
    companyId: companyId.value,
    pageSize: -1,
  };
   budgeModelCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
  } else {
    getBudgetHistory().then((data) => {
    categoryList.value = data;
    categoryTree2.value = listToTree(data,'orderId');

  });
  }
  
};


// 左侧切换
const handleChangeMaterial = () => {
  handleGetCategory()
}

const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (!node.data.children) {
    selectedId.value = node.value;

  }
  
};

const handleChangeCompany = () => {
  handleGetCategory();
};



const handleSelectedIds = () => {
  if(!selectedId.value) {
    MessagePlugin.warning('请选择预算模板');
    return;
  }
  // if(type.value==='2'){
    visible1.value = true;
    return;
  // }
  // emits('save', {
  //   type: type.value,
  //   id: selectedId.value,
  // });
  // visible.value = false;
};

watch(
  () => props.visible,
  async (newVal) => {
    visible.value = newVal;
    if(newVal==true) {
      type.value = '1';
      actived.value = [];
      selectedId.value = null;
      await handleGetCompanySimpleList();
      handleGetCategory();

    }
  }
);

watch(visible, (newVal) => {
  emits('update:visible', newVal);
});

</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  @leftWidth: 300px;

  // .left {
  //   width: @leftWidth;
  // }

  .right {
    flex:1;
    margin-left: 10px;
  }
}
</style>